Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
How to mock all methods of the "chalk" library?

I'm using chalk to style terminal text and I wrote some helper functions to return chalk instances:

/* colorUtils.js */
const chalk = require("chalk");

function redUnderline(text) {
  return chalk.red.underline(text);
}
function greenUnderline(text) {
  return chalk.green.underline(text);
}

module.exports = { redUnderline, greenUnderline };

To test the above functions, I used Jest to write my test suite:

/* colorUtils.test.js */
const chalk = require("chalk");
const { redUnderline, greenUnderline } = require("./colorUtils");

jest.mock("chalk", () => ({
  green: {
    underline: jest.fn(),
  },
  red: {
    underline: jest.fn(),
  },
}));

describe("colorUtils", () => {
  describe("redUnderline", () => {
    it("should return a red, underlined string", () => {
      const result = redUnderline("foo");
      expect(chalk.red.underline).toHaveBeenCalledWith("foo");
    });
  });
  describe("greenUnderline", () => {
    it("should return a green, underlined string", () => {
      const result = greenUnderline("foo");
      expect(chalk.green.underline).toHaveBeenCalledWith("foo");
    });
  });
});

The above test suite passes without problems.

However, in order to test that chalk.red.underline and chalk.green.underline is called properly, I need to mock chalk using jest.mock() with the following code:

jest.mock("chalk", () => ({
  green: {
    underline: jest.fn(),
  },
  red: {
    underline: jest.fn(),
  },
}))

Is there a more compact syntax of jest.mock() such that it mocks all chalk instance methods to become jest.fn()?

I tried using the following mock method:

jest.mock("chalk");

However, the first test will fail:

    TypeError: Cannot read property 'underline' of undefined

      2 |
      3 | function redUnderline(text) {
    > 4 |   return chalk.red.underline(text);
        |                    ^
      5 | }
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda